package guda.house.web.action.bill;

import guda.grape.autogen.common.page.BizResult;
import guda.grape.util.RequestUtil;
import guda.house.biz.BillPayBiz;
import guda.house.biz.beans.vo.BillPayXlsVO;
import guda.house.biz.beans.vo.JsonResult;
import guda.house.biz.constants.CommonResultCode;
import guda.house.biz.form.bill.BillPaySearchForm;
import guda.house.biz.query.BillPayQuery;
import guda.house.biz.security.AppUtil;
import guda.house.biz.util.ErrorCode;
import guda.house.biz.util.ExportExcelUtil;
import guda.house.biz.util.PriceUtil;
import guda.house.dal.dataobject.BillPayDO;
import guda.house.web.helper.ResponseHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by well on 15/11/17.
 */
@Controller
@RequestMapping(value = "bill/pay")
public class PayAction {

    @Autowired
    private BillPayBiz billPayBiz;

    @RequestMapping(value = "list.htm", method = RequestMethod.GET)
    public String list(HttpServletRequest request, ModelMap modelMap, BillPaySearchForm billPaySearchForm) {
        int pageId = RequestUtil.getInt(request, "pageNo");
        int pageSize = RequestUtil.getInt(request, "pageSize");
        BillPayQuery billPayQuery = new BillPayQuery();
        if(billPaySearchForm.getVillageId() == null) {
            List<Long> villageIdList = AppUtil.getVillageIdList();
            if (villageIdList.size() > 0) {
                billPaySearchForm.setVillageId(villageIdList.get(0));
            }
        }
        billPayQuery.setPageNo(pageId);
        billPayQuery.setPageSize(pageSize);
        billPayQuery.setVillageId(billPaySearchForm.getVillageId());
        billPayQuery.setBuildingId(billPaySearchForm.getBuildingId());
        billPayQuery.setUnitId(billPaySearchForm.getUnitId());
        billPayQuery.setSuiteId(billPaySearchForm.getSuiteId());
        modelMap.put("query", billPayQuery);
        BizResult bizResult = billPayBiz.listForPayLog(billPayQuery);
        BizResult bizResult1 = billPayBiz.initSearchForm(billPaySearchForm);
        modelMap.putAll(bizResult1.data);
        if (bizResult.success) {
            modelMap.putAll(bizResult.data);
            return "bill/pay/list.vm";
        } else {
            return "redirect:/error.htm?code=" + bizResult.code;
        }
    }

    @RequestMapping(value = "detail.htm", method = RequestMethod.GET)
    public String detail(HttpServletRequest request, ModelMap modelMap, BillPaySearchForm billPaySearchForm) {
        long billPayId = RequestUtil.getLong(request, "billPayId");


        BizResult bizResult = billPayBiz.queryDetail(billPayId);
        modelMap.putAll(bizResult.data);
        if (bizResult.success) {
            modelMap.putAll(bizResult.data);
            return "bill/pay/detail.vm";
        } else {
            return "redirect:/error.htm?code=" + bizResult.code;
        }
    }

    @RequestMapping(value = "export.do", method = RequestMethod.GET)
    public void export(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap, BillPaySearchForm billPaySearchForm) {

        String filedisplay = null;
        try {
            filedisplay = URLEncoder.encode("缴费记录.xls", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType("application/x-download; charset=UTF-8");
        response.addHeader("Content-Disposition", "attachment; filename=" + filedisplay);

        BillPayQuery billPayQuery = new BillPayQuery();
        billPayQuery.setPageNo(1);
        billPayQuery.setPageSize(10000);
        billPayQuery.setVillageId(billPaySearchForm.getVillageId());
        billPayQuery.setBuildingId(billPaySearchForm.getBuildingId());
        billPayQuery.setUnitId(billPaySearchForm.getUnitId());
        billPayQuery.setSuiteId(billPaySearchForm.getSuiteId());
        modelMap.put("query", billPayQuery);
        BizResult bizResult = billPayBiz.listForPayLog(billPayQuery);
        List<BillPayDO> billPayList = (List<BillPayDO>)bizResult.data.get("billPayList");
        List<BillPayXlsVO> billPayXlsVOList = new ArrayList<BillPayXlsVO>(billPayList.size());
        for(BillPayDO billPayDO:billPayList){
            BillPayXlsVO billPayXlsVO = new BillPayXlsVO();
            billPayXlsVO.setDeposit(PriceUtil.formatCNY(billPayDO.getPayTotalCharge()));
            billPayXlsVO.setMoney(PriceUtil.formatCNY(billPayDO.getPayTotal()));
            billPayXlsVO.setPayComment(billPayDO.getPayComment());
            billPayXlsVO.setPayDesc(billPayDO.getPayDesc());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            billPayXlsVO.setPayTime(simpleDateFormat.format(billPayDO.getGmtCreate()));
            billPayXlsVO.setPayWay(billPayDO.getPayType());

            billPayXlsVO.setSuiteName(getSuiteName(billPayDO.getSuiteId()));
            billPayXlsVOList.add(billPayXlsVO);
        }
        String[] headers = new String[]{"房号","缴费金额(元)","支付方式","手续费(元)","缴费时间","详情","备注"};
        String[] fields = new String[]{"suiteName","money","payWay","deposit","payTime","payDesc","payComment"};
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            ExportExcelUtil.exportExcel("缴费记录",headers,fields,billPayXlsVOList,outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String getSuiteName(Long suiteId){
        String villageName = AppUtil.getVillageBySuiteId(suiteId).getVillageName();
        String buildingName = AppUtil.getBuildingBySuiteId(suiteId).getBuildingName();
        String unitName = AppUtil.getUnitBySuiteId(suiteId).getUnitName();
        String suiteName = AppUtil.getSuiteBySuiteId(suiteId).getSuiteName();
        StringBuilder buf = new StringBuilder();
        buf.append(villageName).append(buildingName).append("(幢)").append(unitName).append("(单元)")
                .append(suiteName).append("(房号)");
        return buf.toString();
    }


}
